<template>
  <a-upload
    :accept="accept"
    :customRequest="uploadFile"
    :before-upload="(file) => beforeUpload(file)"
    :file-list="fileList"
    name="file"
    :multiple="true"
  >
    <div v-if="fileList.length < maxFile">
      <a-button> <a-icon type="upload" /> {{ label }} </a-button>
    </div>
  </a-upload>
</template>
<script>
import { aplUploadFile } from '@/api/apply/apl_file.js'
import { getFileSize } from '../../utils/util.js'
export default {
  props: {
    accept: {
      type: String,
      default: '.pdf',
    },
    maxFile: {
      type: Number,
      default: 1,
    },
    // 标题
    label: {
      type: String,
      require: true,
    },
    // 字段
    field: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [], // 文件列表
      loading: false, // 上传状态
      FILESIZE: 20, // 文件最大值
    }
  },
  created() {},
  methods: {
    // 文件上传前
    beforeUpload(file) {
      // 校验文件大小
      return new Promise(async (resolve, reject) => {
        let fileSize = getFileSize(file.size)
        if (Number(fileSize) > this.FILESIZE) {
          this.$message.warning(`文件大小不能超过${this.FILESIZE}M`)
          return reject()
        } else {
          return resolve()
        }
      })
    },
    // 文件上传
    uploadFile(data) {
      this.loading = true
      aplUploadFile(data.file).then((res) => {
        if (res.code == 0) {
          data.onSuccess()
          let file = {
            uid: res.data.id,
            name: res.data.filename,
            status: 'done',
            url: res.data.url,
          }
          this.fileList.push(file)
          this.$listeners.f_setVariable(this.field, file.uid)
        }
        this.loading = false
        console.log('上传后', this.fileList)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
</style>
